<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="课题名称" prop="topicName">
        <el-input
          v-model="queryParams.topicName"
          clearable
          placeholder="请输入课题名称"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课题来源" prop="topicSource">
        <el-input
          v-model="queryParams.topicSource"
          clearable
          placeholder="请输入课题来源"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTimeRange">
        <el-date-picker
          v-model="queryParams.startTimeRange"
          :picker-options="pickerOptions"
          align="right"
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          type="datetimerange"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:topic:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >创建课题
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:sample:export']"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
        >批量导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="24">
      <el-col v-for="(item, index) in topicList" :key="index" :span="6">
        <el-card :body-style="{ padding: '0px' }">
          <div slot="header" class="clearfix">
            <el-link :underline="false" @click="jumpToTask(item)">{{ item.topicName }}</el-link>
            <time class="time">{{ item.startTime }}</time>
          </div>
          <div style="padding: 14px;">
            <el-row :gutter="24">
              <el-col :span="11" align="middle" type="flex">
                <el-button type="text" @click="jumpToTask(item)">
                  <div><span class="taskContent">{{ item.doneTaskCount }}</span></div>
                  <div><span class="taskTitle">已完成任务</span></div>
                </el-button>
              </el-col>
              <el-col :span="2">
                <el-divider direction="vertical"></el-divider>
              </el-col>
              <el-col :span="11" align="middle" type="flex">
                <el-button type="text" @click="jumpToTask(item)">
                  <div><span class="taskContent">{{ item.unDoneTaskCount }}</span></div>
                  <div><span class="taskTitle">待完成任务</span></div>
                </el-button>
              </el-col>
            </el-row>
            <div align="middle" class="bottom clearfix" style="margin-top: 24px" type="flex">
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-link :underline="false" @click="crfSet(item)">
                    <i class="el-icon-s-order" style="font-size: 28px"></i>
                    <div class="topicBtnTitle">CRF设置</div>
                  </el-link>
                </el-col>
                <el-col :span="8">
                  <el-link :underline="false" @click="memberSet(item)">
                    <i class="el-icon-user-solid" style="font-size: 28px"></i>
                    <div class="topicBtnTitle">成员设置</div>
                  </el-link>
                </el-col>
                <el-col :span="8">
                  <el-popover
                    placement="right-start"
                    trigger="click"
                    width="150"
                  >
                    <ul>
                      <li>
                        <el-link v-hasPermi="['research:topic:edit']" :underline="false" icon="el-icon-edit"
                                 @click="handleUpdate(item)"
                        >编辑
                        </el-link>
                      </li>
                      <div style="height: 10px"></div>
                      <li>
                        <el-link v-hasPermi="['research:topic:remove']" :underline="false" icon="el-icon-delete"
                                 @click="handleDelete(item)"
                        >删除
                        </el-link>
                      </li>
                    </ul>
                    <el-link slot="reference" :underline="false">
                      <i class="el-icon-s-tools" style="font-size: 28px"></i>
                      <div class="topicBtnTitle">课题设置</div>
                    </el-link>
                  </el-popover>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改课题 对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课题编号" prop="topicCode">
          <el-input v-model="form.topicCode" placeholder="请输入课题编号"/>
        </el-form-item>
        <el-form-item label="课题名称" prop="topicName">
          <el-input v-model="form.topicName" placeholder="请输入课题名称"/>
        </el-form-item>
        <el-form-item label="课题来源" prop="topicSource">
          <el-input v-model="form.topicSource" placeholder="请输入课题来源"/>
        </el-form-item>
        <el-form-item label="研究目的" prop="researchPurposes">
          <el-input v-model="form.researchPurposes" placeholder="请输入内容" type="textarea"/>
        </el-form-item>
        <el-form-item label="研究方法" prop="researchMethod">
          <el-input v-model="form.researchMethod" placeholder="请输入内容" type="textarea"/>
        </el-form-item>
        <el-form-item label="预期结果" prop="expectedResult">
          <el-input v-model="form.expectedResult" placeholder="请输入内容" type="textarea"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" clearable
                          placeholder="选择开始时间"
                          size="small"
                          type="date"
                          value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="form.endTime" clearable
                          placeholder="选择结束时间"
                          size="small"
                          type="date"
                          value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="memberOpen" append-to-body title="成员设置" width="680px">
      <el-transfer v-model="memberValue" :data="memberData" :props="memberProps"></el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMember">确 定</el-button>
        <el-button @click="cancelMember">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="crfOpen" append-to-body title="选择CRF模板" width="500px">
      <el-table
        ref="crfTable"
        :data="customForms"
        highlight-current-row
        style="width: 100%"
        @current-change="handleCrfTableChange"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column align="center" label="表单Key" property="formKey"></el-table-column>
        <el-table-column align="center" label="表单名称" property="formName"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCrf">确 定</el-button>
        <el-button @click="cancelCrf">取 消</el-button>
      </div>
    </el-dialog>
    <export-preview :batchExportData="batchExportData" :batchVisible.sync="batchVisible"></export-preview>
  </div>
</template>

<script>
import {
  addMembers,
  addTopic,
  delTopic,
  getMembers,
  getTopic,
  listAllAndFrom,
  listTopic,
  updateTopic
} from '@/api/research/topic'
import { listUser } from '@/api/system/user'
import { allForm } from '@/api/tool/form'
import exportPreview from './module/exportPreview'

export default {
  name: 'Topic',
  components: {
    exportPreview
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课题 表格数据
      topicList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 选中的课题
      selectTopic: {},
      // 成员设置对话框
      memberOpen: false,
      // 选中的成员
      memberValue: [],
      // 用户列表
      memberData: [],
      memberProps: {
        key: 'userId',
        label: 'nickName'
      },
      // crf对话框
      crfOpen: false,
      // crf自定义表单
      customForms: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'DESC',
        topicCode: undefined,
        topicName: undefined,
        topicSource: undefined,
        researchPurposes: undefined,
        researchMethod: undefined,
        expectedResult: undefined,
        startTime: undefined,
        endTime: undefined,
        startTimeRange: undefined
      },
      // 表单参数
      form: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 表单校验
      rules: {
        topicCode: [{ required: true, trigger: 'blur', message: '课题编号不能为空' }, {
          max: 50,
          trigger: 'blur',
          message: '课题编号不能超过50个字符'
        }],
        topicName: [{ required: true, trigger: 'blur', message: '课题名称不能为空' }, {
          max: 100,
          trigger: 'blur',
          message: '课题名称不能超过100个字符'
        }],
        topicSource: { max: 50, trigger: 'blur', message: '课题来源不能超过50个字符' }
      },

      //批量导出数据
      batchExportData: [],
      batchVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 跳转到课题任务
    jumpToTask(item) {
      this.$router.push({
        path: '/project/TopicTask',
        query: {
          topicId: item.topicId
        }
      })
    },
    handleCrfTableChange(val) {
      this.selectTopic.formKey = val.formKey
    },
    // CRF设置
    crfSet(row) {
      this.selectTopic = row
      this.crfOpen = true
      let queryForm = {}
      queryForm.formType = 'crf'
      allForm(queryForm).then(response => {
        this.customForms = response.data
        if (row.formKey) {
          this.customForms.forEach((item, index) => {
            if (item.formKey === row.formKey) {
              this.$refs.crfTable.setCurrentRow(item)
            }
          })
        }
      })
    },
    submitCrf() {
      updateTopic(this.selectTopic).then(response => {
        this.msgSuccess('CRF设置成功')
        this.crfOpen = false
        this.getList()
      })
    },
    cancelCrf() {
      this.crfOpen = false
    },
    // 成员设置
    memberSet(row) {
      this.memberValue = []
      this.memberData = []
      this.memberOpen = true
      this.selectTopic = row

      let queryParam = {}
      listUser(queryParam).then(res => {
        this.memberData = res.rows
      })
      getMembers(row.topicId).then(response => {
        this.memberValue = response.data
      })
    },
    // 成员设置 提交
    submitMember() {
      let topicUsers = []
      this.memberValue.forEach((item, index) => {
        let topicUser = {}
        topicUser.topicId = this.selectTopic.topicId
        topicUser.userId = item
        topicUsers.push(topicUser)
      })
      addMembers(topicUsers).then(response => {
        this.memberOpen = false
        this.msgSuccess('成员设置成功')
      })
    },
    // 成员设置对话框 取消
    cancelMember() {
      this.memberOpen = false
    },
    /** 查询课题 列表 */
    getList() {
      this.loading = true
      listTopic(this.queryParams).then(response => {
        this.topicList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.selectTopic = {}
      this.form = {
        topicId: undefined,
        topicCode: undefined,
        topicName: undefined,
        topicSource: undefined,
        researchPurposes: undefined,
        researchMethod: undefined,
        expectedResult: undefined,
        startTime: undefined,
        endTime: undefined,
        startTimeRange: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加课题 '
    },

    /**
     * @description: 批量导出
     * @return {*}
     */
    handleExport() {
      listAllAndFrom().then(response => {
        this.batchExportData = response.data
        this.batchVisible = !this.batchVisible
      })
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const topicId = row.topicId
      getTopic(topicId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改课题 '
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.topicId != null) {
            updateTopic(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addTopic(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const topicIds = row.topicId
      this.$confirm('是否确认删除课题 编号为"' + topicIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delTopic(topicIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    }
  }
}
</script>
<style scoped>
.time {
  font-size: 13px;
  color: #999;
  float: right;
  padding: 3px 0
}

.el-divider--vertical {
  height: 56px;
}

.taskContent {
  font-weight: 200;
  font-size: 36px;
  color: #1a70ff
}

.taskTitle {
  margin-top: 16px;
  font-size: 16px;
  color: #888888
}

.topicBtnTitle {
  margin-top: 5px;
  font-size: 16px;
  color: #888888
}

ul li {
  list-style: none;
}
</style>
